package com.zhy.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ControllerAdvice声明一个控制器建言，@ControllerAdvice组合了@Component注解，所以自动注册为Spring的Bean
 * Created by zhy on 2017/5/5.
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {

    public ExceptionHandlerAdvice() {
        System.out.println("ExceptionHandlerAdvice初始化了");
    }

    /**
     * @ExceptionHandler在此处定义全局处理
     * @ExceptionHandler的value属性可过滤拦截的条件，在此处我们可以看出我们拦截所有的Exception
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception e, WebRequest request) {
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("errorMessage", e.getMessage());
        return mv;
    }

    /**
     * 此处使用@ModelAttribute注解将键值对添加到全局，所有注解的@RequestMapping的方法可获得此键值对
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("msg", "额外信息");
    }

    /**
     * 通过@InitBinder注解定制WebDataBinder
     * WebDataBinder用来自动绑定前台请求参数到Model中
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.setDisallowedFields("id");
    }
}
